<template>
  <epm-manager-layout>
    <template v-slot:title>
      <h1>新建号卡</h1>
    </template>
    <template v-slot:main>
      <div class="ring_container">
        <div style="margin: 20px 0;">

          <p style="margin-bottom: 20px;">
            <span style="font-size: 12px;margin-right: 10px;">添加方式：</span>
            <el-radio-group v-model="addType">
              <el-radio-button label="1">手动添加</el-radio-button>
              <el-radio-button label="2">导入添加</el-radio-button>
            </el-radio-group>
          </p>

          <div v-show="addType==='1'">
            <el-table :data="tableData" style="width: 100%;">
              <el-table-column type="index" width="50"></el-table-column>
              <el-table-column label="卡号" width="180">
                <template slot-scope="scope">
                  <el-input type="text" placeholder="请输入卡号" v-model="scope.row.cardNo" maxlength="11"
                            onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="运营商">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.operator" placeholder="请选择运营商" @change="changeOperator(scope.row)">
                    <el-option v-for="{code,name} in operatorCode" :label="name" :value="code"
                               :key="code"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="靓号类型">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.aaaaNoTypeId" placeholder="请选择靓号类型" clearable
                             :disabled="!scope.row.operator"
                             @change="()=>{if(!!scope.row.aaaaNoTypeId) scope.row.telecomPackageId = aaaaNoTypeList.find(a=>a.id === scope.row.aaaaNoTypeId).packageId}">
                    <el-option v-for="{id,aaaaNoTypeName} in aaaaNoTypeList" :label="aaaaNoTypeName" :value="id"
                               :key="id"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="最低消费套餐">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.telecomPackageId"
                             :disabled="!!scope.row.aaaaNoTypeId || !scope.row.operator" placeholder="请选择最低消费套餐">
                    <el-option v-for="{id,packageName} in effectivePackageList" :label="packageName" :value="id"
                               :key="id"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="最低预存" width="120">
                <template slot-scope="scope">
                  <el-input type="text" placeholder="请输入" v-model="scope.row.minPreStorm" maxlength="6"
                            onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="合约期" width="120">
                <template slot-scope="scope">
                  <el-input type="text" placeholder="请输入" v-model="scope.row.contractPeriod" maxlength="6"
                            onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="开卡费" width="120">
                <template slot-scope="scope">
                  <el-input type="text" placeholder="请输入" v-model="scope.row.cardOpeningFee" maxlength="6"
                            onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" icon="el-icon-delete" circle
                             @click="tableData.splice(scope.$index,1);"/>
                </template>
              </el-table-column>
            </el-table>
            <div style="text-align: center">
              <el-button type="primary" @click="add" class="ring_add">+ 添加号卡</el-button>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align: center">
            <span>
              <el-button type="danger" @click="cancel">取消</el-button>
              <el-button type="primary" :disabled="tableData.length===0" @click="save" :loading="loading">保存</el-button>
            </span>
            </div>
          </div>
          <div v-show="addType==='2'">
            <span
                style="font-size: 12px;margin-right: 10px;line-height: 30px; display: inline-block;transform: translate(0, -104%);">导入文件：</span>
            <el-upload class="upload-demo" :action="uploadUrl" :headers="{'token':localStorage.getItem('token')}"
                       accept=".xls,.xlsx" :before-upload="beforeUpload"
                       :file-list="fileList" :on-success="success" :limit="1" :show-file-list="false" :on-error="error">
              <el-button class="dialog-btn" type="primary" plain><i class="iconfont iconshangchuan"
                                                                    style="font-size:12px; ">&nbsp;&nbsp;点击导入</i>
              </el-button>
              <div slot="tip" class="el-upload__tip">
                <span><i class="el-icon-info"></i>只能上传xls/xlsx文件，且不超过3M。<el-link type="primary"
                                                                                 icon="el-icon-c-scale-to-original"
                                                                                 @click="downLoadTemplate">点击下载模板</el-link></span>
              </div>
            </el-upload>
            <div v-show="importRetData.length>0" style="width: 100%;margin-top: 50px">
              <h5 style="color: red">导入失败号卡</h5>
              <el-table :data="importRetData">
                <el-table-column prop="cardNo" label="卡号"></el-table-column>
                <el-table-column prop="msg" label="失败原因"></el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </template>
  </epm-manager-layout>
</template>

<script>
import request from "@/utils/Request";
import {operatorCode} from "@/common/PublicCode";
import EventBus from '@/utils/EventBus'
import {downLoad} from "@/utils/DownLoadUtil";


export default {
  name: "AddCardNo",
  data() {
    return {
      localStorage: localStorage,
      addType: "1",
      effectivePackageList: [],
      tableData: [],
      operatorCode: operatorCode,
      aaaaNoTypeList: [],
      uploadUrl: `${window.config.BASE_API}/noCard/importList`,
      fileList: [],
      importRetData: [],
      loading: false
    }
  },
  mounted() {
    this.initEffectivePackageList();
    this.initAAAANoTypeList();
  },
  methods: {
    downLoadTemplate() {
      downLoad("/common/downLoad", {fileName: '号卡导入模板.xlsx', filePath: '/号卡导入模板.xlsx'}, '下载模板失败');
    },
    async cancel() {
      if (this.tableData.length > 0) {
        const confirm = await this.$confirm('是否确认取消?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return true;
        }).catch(() => {
          return false;
        });
        if (!confirm) {
          return;
        }
        this.tableData = [];
      }
      this.$router.history.go(-1);
    },
    beforeUpload(file) {
      if (file.size > 3145728) {
        this.$message({type: 'warning', message: '最大只能上传3m的文件'})
        return false
      } else {
        this.$message({type: 'success', message: '导入中，请耐心等待'})
        return true
      }
    },
    success(response, file) {
      this.fileList = [];
      if (response.success) {
        this.importRetData = response.data;
        if (response.data.length > 0) {
          this.$message({type: "warning", message: "上传完毕，请查看导入失败号卡"});
        } else {
          this.$message({type: "success", message: "上传完毕"});
        }
        EventBus.$emit('saveCardNoSuccess');
      } else {
        this.$message({type: "error", message: "上传失败"});
      }
    },
    error() {
      this.$message({type: "error", message: "上传时出错"});
    },
    changeOperator(_row) {
      this.initEffectivePackageList({operator: _row.operator});
      this.initAAAANoTypeList({operator: _row.operator});
      _row.aaaaNoTypeId = '';
      _row.telecomPackageId = '';
    },
    async save() {
      if (this.tableData.filter(f => !f.cardNo || !f.operator || !f.telecomPackageId).length > 0) {
        this.$message({type: 'warning', message: "无法保存, 存在未完成的号卡"});
        return;
      }
      const filter = this.tableData.filter(f => f.cardNo.length !== 11).map(f => f.cardNo);
      if (filter.length > 0) {
        this.$message({type: 'warning', message: `无法保存, 以下卡号不足11位：${JSON.stringify(filter)}`});
        return;
      }
      if (this.tableData.length === 0) {
        return;
      }
      const validateList = await request.post('/noCard/validateList', this.tableData).then(({data}) => {
        if (!data.success) {
          this.$message({type: 'warning', message: `存在重复卡号:${JSON.stringify(data.data)}`});
          return false;
        } else {
          return true;
        }
      }).catch(err => {
        this.$message({type: 'error', message: "保存号卡失败"});
        console.log(err)
      })
      if (validateList) {
        this.loading = true;
        request.post('/noCard/saveList', this.tableData).then(({data}) => {
          if (data.success) {
            EventBus.$emit('saveCardNoSuccess')
            this.tableData = [];
            this.$message({type: 'success', message: "保存号卡成功，请返回卡号管理页面查看新号卡"});
          } else {
            this.$message({type: 'warning', message: `${data.message}：${JSON.stringify(data.data)}`});
          }
        }).catch(err => {
          this.$message({type: 'error', message: "保存号卡失败"});
          console.log(err)
        }).finally(() => {
          this.loading = false;
        })
      }
    },
    add() {
      let item = {
        cardNo: '',
        operator: '',
        aaaaNoTypeId: '',
        telecomPackageId: '',
        minPreStorm: '0',
        contractPeriod: '0',
        cardOpeningFee: '0'
      };
      this.tableData.push(item);
    },
    initAAAANoTypeList({operator} = {}) {
      request.get('/AAAANoType/getList', {params: {operator}}).then(({data}) => {
        if (data.success) {
          this.aaaaNoTypeList = data.data;
        }
      }).catch(err => {
        this.$message({type: 'error', message: "查询靓号类型列表失败"});
        console.log(err)
      })
    },
    initEffectivePackageList({operator} = {}) {
      request.get('/telecomPackage/getEffectiveList', {params: {operator}}).then(({data}) => {
        if (data.success) {
          this.effectivePackageList = data.data;
        }
      }).catch(err => {
        this.$message({type: 'error', message: "查询套餐列表失败"});
        console.log(err)
      })
    },
  }
}
</script>

<style scoped>

.ring_container {
  min-height: 500px;
  position: relative;
}

.upload-demo {
  display: inline-block;
}

.el-upload__tip {
  margin-left: 0;
}

.ring_add {
  background: #FAFAFA;
  border: 1px #f2f2f2 dashed;
  color: #646C9A;
  width: 100%;
  margin: 10px auto;
}

.ring_add:hover {
  background: #e6edff;
  border: 1px #dce7ff dashed;
  color: #5B73FF;
}

.dialog-footer {
  position: absolute;
  bottom: 0;
  height: 70px;
  align-items: center;
  width: 100%;
  display: flex;
  justify-content: center;
}

.el-table__empty-text {
  line-height: 40px;
}

</style>